package com.xw.unification.interceptor;

import com.xw.unification.annotations.IgnoreSignatureCheck;
import com.xw.unification.annotations.SignatureCheck;
import com.xw.unification.annotations.SignatureCheckDefinition;
import com.xw.unification.config.WebUnificationMvcProperties;
import com.xw.unification.config.WebUnificationMvcProperties.SignatureCheckProperties;
import com.xw.unification.config.WebUnificationMvcProperties.UnifiedResponseProperties;
import com.xw.unification.constant.UnificationConstant.SignatureCheckConstant;
import com.xw.unification.entity.SignatureCheckContext;
import com.xw.unification.exception.SignatureCheckException;
import com.xw.unification.interfaces.ResultCodeEnumerable;
import com.xw.unification.utils.AnnotationDetector;
import com.xw.unification.helper.SignatureHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 统一签名验证拦截器
 */
public class RequestSignatureCheckInterceptor implements UnifiedRequestInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestSignatureCheckInterceptor.class);

    private static final char K_V_SPLITTER = '=';

    private static final char K_V_PAIR_SPLITTER = '&';

    private static final char[] K_V_PAIR_SPLITTERS = {K_V_PAIR_SPLITTER};

    private final SignatureCheckProperties checkProperties;

    private final ResultCodeEnumerable errEnum;

    public RequestSignatureCheckInterceptor(WebUnificationMvcProperties properties) {
        this.checkProperties = properties.getApiSignatureCheck();
        UnifiedResponseProperties responseProperties = properties.getUnifiedResponse();
        if (responseProperties.isEnable() && responseProperties.getResult() != null) {
            errEnum = responseProperties.getResult()
                    .getEnumByClass(checkProperties.getCheckErrorEnumName());
        } else {
            errEnum = null;
        }
    }

    private void testInputStream(HttpServletRequest request) {
        ServletInputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            byte read;
            List<Byte> byteList = new ArrayList<>();
            while ((read = (byte) inputStream.read()) >= 0) {
                byteList.add(read);
            }
            byte[] bytes = new byte[byteList.size()];
            for (int i = 0; i < byteList.size(); i++) {
                bytes[i] = byteList.get(i);
            }
            LOGGER.info("request body: {}", new String(bytes, StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler,
                              ApplicationContext ctx, WebUnificationMvcProperties properties)
            throws Exception {
        if (!checkProperties.isEnable()) {
            // 未开启验签, 直接 pass
            return true;
        }
        if (!needSignatureCheck(handler)) {
            return true;
        }

        // 构成验签上下文
        SignatureCheckDefinition checkDefinition = getSignatureCheckAnnotation(handler);
        SignatureCheckContext checkContext = new SignatureCheckContext(checkProperties);
        if (checkDefinition != null) {
            checkContext.combineSignatureCheckAnnotation(checkDefinition);
        }

        // 开始根据验签上下文规则生成签名
        SignatureHelper signatureHelper = new SignatureHelper() {
            @Override
            protected String setValueWhenNoOrMultiValidation(String key, List<String> valueList) throws RuntimeException {
                throw generateSignatureCheckException(properties,
                        String.format("%s validation signature, key name: %s", valueList == null ? "No" : "Not single", key),
                        null
                );
            }
            @Override
            protected String handleWhenNoOrMultiSignatureKey(String key, List<String> valueList) throws RuntimeException {
                throw generateSignatureCheckException(properties,
                        String.format("%s signature key, key name: %s", valueList == null ? "No" : "Not single", key),
                        null
                );
            }
        };

        String content = signatureHelper.signature(request == null ? null : request.getQueryString(), checkContext);
        String validation = checkContext.getValidation();
        if (validation != null && validation.equals(content)) {
            LOGGER.info("Signature validation success");
            return true;
        } else {
            throw generateSignatureCheckException(properties, "Signature is invalid", null);
        }
    }

    private SignatureCheckDefinition getSignatureCheckAnnotation(HandlerMethod handlerMethod) {
        if (handlerMethod == null || handlerMethod.getMethod() == null) {
            return null;
        }
        Method method = handlerMethod.getMethod();
        if (method.getDeclaringClass() == null) {
            return null;
        }
        return Optional.ofNullable(AnnotationDetector.findAnnotation(method, SignatureCheckDefinition.class))
                .orElse(AnnotationDetector.findAnnotation(method.getDeclaringClass(), SignatureCheckDefinition.class));
    }

    /**
     * 判断是否需要签名验证
     *
     * @param handler   处理器方法
     * @return boolean
     */
    private boolean needSignatureCheck(HandlerMethod handler) {
        Method method = handler.getMethod();
        if (Optional.ofNullable(AnnotationDetector.findAnnotation(method, IgnoreSignatureCheck.class))
                .orElse(AnnotationDetector.findAnnotation(method.getDeclaringClass(), IgnoreSignatureCheck.class)) != null) {
            return false;
        }
        if (checkProperties.isGlobalCheck()) {
            return true;
        }
        Class<?> declaringClass = method.getDeclaringClass();
        String pkgName = null;
        String className = null;
        if (declaringClass != null) {
            Package pkg = declaringClass.getPackage();
            pkgName = pkg == null ? null : pkg.getName();
            className = declaringClass.getCanonicalName();
        }
        if (pkgName != null) {
            for (String pkg : checkProperties.getCheckPackages()) {
                if (pkg != null && pkgName.startsWith(pkg)) {
                    return true;
                }
            }
        }
        if (className != null) {
            for (String typeName : checkProperties.getCheckClasses()) {
                if (className.equals(typeName)) {
                    return true;
                }
            }
        }
        return Optional.ofNullable(AnnotationDetector.findAnnotation(method, SignatureCheck.class))
                .orElse(AnnotationDetector.findAnnotation(method.getDeclaringClass(), SignatureCheck.class)) != null;
    }

    private Map<String, List<String>> getParamMap(String queryString, String encodingType, boolean ignoreEmptyValue) {
        try {
            queryString = URLDecoder.decode(Optional.ofNullable(queryString).orElse(""), encodingType);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Unsupported encoding type: " + encodingType, e);
        }
        Map<String, List<String>> map = new HashMap<>();
        StringBuilder keyBuilder = new StringBuilder();
        StringBuilder valueBuilder = new StringBuilder();
        List<String> valueList = null;
        char ch;
        boolean readValue = false;
        for (int i = 0; i < queryString.length(); i++) {
            ch = queryString.charAt(i);
            if (!readValue) {
                // 读 key
                if (ch != K_V_SPLITTER) {
                    keyBuilder.append(ch);
                } else {
                    // 切换读 value
                    readValue = true;
                    valueList = map.getOrDefault(keyBuilder.toString(), new ArrayList<>());
                }
            } else {
                // 读 value
                if (isInCharArray(K_V_PAIR_SPLITTERS, ch)) {
                    // 切换读 key
                    if (valueList != null && (!ignoreEmptyValue || valueBuilder.length() > 0)) {
                        valueList.add(valueBuilder.toString());
                    }
                    valueBuilder.delete(0, valueBuilder.length());
                    if (valueList != null && !valueList.isEmpty() && keyBuilder.length() > 0) {
                        map.put(keyBuilder.toString(), valueList);
                    }
                    keyBuilder.delete(0, keyBuilder.length());
                    readValue = false;
                } else {
                    valueBuilder.append(ch);
                }
            }
        }
        if (valueList != null && (!ignoreEmptyValue || valueBuilder.length() > 0)) {
            valueList.add(valueBuilder.toString());
        }
        if (valueList != null && !valueList.isEmpty() && keyBuilder.length() > 0) {
            map.put(keyBuilder.toString(), valueList);
        }
        return map;
    }

    private boolean isInCharArray(char[] charArray, char ch) {
        if (charArray == null) {
            return false;
        }
        for (char c : charArray) {
            if (c == ch) {
                return true;
            }
        }
        return false;
    }

    private SignatureCheckException generateSignatureCheckException(WebUnificationMvcProperties properties, String log, String message)
            throws SignatureCheckException {
        LOGGER.error(log);
        if (properties != null && properties.getUnifiedResponse() != null) {
            UnifiedResponseProperties responseProperties = properties.getUnifiedResponse();
            if (errEnum != null) {
                if (message != null) {
                    return new SignatureCheckException(errEnum, message, null);
                } else {
                    return new SignatureCheckException(errEnum);
                }
            } else {
                LOGGER.warn("Signature check error enum can not be fount, enum name: "
                        + checkProperties.getCheckErrorEnumName());
            }
        }
        return new SignatureCheckException(SignatureCheckConstant.DEFAULT_SIGNATURE_CHECK_ERROR_CODE, log, null);
    }

}
